package com.zzxx.wechat.controller;


import com.zzxx.wechat.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Controller
public class WechatController {

    @Autowired
    WxMpService wxMpService;

    @Autowired
    WxMpMessageRouter wxMpMessageRouter;

  //  @GetMapping(value = "/wechat", produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String doGet(@RequestParam("signature") String signature,
                        @RequestParam("timestamp") String timestamp,
                        @RequestParam("nonce") String nonce,
                        @RequestParam("echostr") String echostr) {

        if (SignUtil.checkSignature(signature, timestamp, nonce))
            return echostr;
        return "ok";

    }


    @PostMapping(value = "/wechat", produces = "application/xml; charset=UTF-8")
    @ResponseBody
    public String wechat(@RequestBody String requestBody,
                         @RequestParam("signature") String signature,
                         @RequestParam("timestamp") String timestamp,
                         @RequestParam("nonce") String nonce) {
        log.info("校验入参:signature:{},timestamp:{},nonce:{},requestBody:{}", signature, timestamp, nonce, requestBody);

        // 校验消息是否来自微信
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }
        // 解析消息体，封装为对象
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
        WxMpXmlOutMessage outMessage;
        try {
            // 将消息路由给对应的处理器，获取响应
            outMessage = wxMpMessageRouter.route(inMessage);
        } catch (Exception e) {
            log.error("微信消息路由异常", e);
            outMessage = null;
        }
        // 将响应消息转换为xml格式返回
        return outMessage == null ? "" : outMessage.toXml();
    }


}
